package com.sunnada.edu.system.login.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.sunnada.edu.system.login.service.LoginMethods;
import com.sunnada.edu.system.login.service.LoginService;
import com.sunnada.edu.system.pub.common.BasicController;
import com.sunnada.edu.system.pub.common.Common;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.common.LogInfo;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.common.RandomTool;
import com.sunnada.edu.system.pub.listener.SessionListener;
import com.sunnada.edu.system.pub.util.DESJAVA;
import com.sunnada.edu.system.pub.util.ImageUtil;
import com.sunnada.edu.system.pub.util.Utils;

@Controller
@RequestMapping("/loginController")
public class LoginController extends BasicController {

	@Resource
	LoginService loginService;

	/**
	 * 处理登录请求
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/login")
	public void login(HttpServletRequest request, HttpServletResponse response) {
		JSONObject returnJson = new JSONObject();
		String userLoginCode = request.getParameter("userLoginCode");
		String password = request.getParameter("password");
		String key = (String) request.getSession().getAttribute(Constants.DESSTRING); // 密钥
		userLoginCode = DESJAVA.strDec(userLoginCode, key, null, null);// 前端解密
		password = DESJAVA.strDec(password, key, null, null);// 前端解密
		userLoginCode = Utils.xssEncode(userLoginCode);
		//String ip = Utils.getIp(request);
		//String codeimage = request.getParameter("codeimage"); // 图形验证码
		//String checkCode = request.getSession().getAttribute("CheckCode") + ""; // 获取服务器保存验证码
		//if (checkCode.equalsIgnoreCase(codeimage) || codeimage.equals("8888")) {
			/** 去掉非法字符 */
			userLoginCode = Utils.devExceptString(userLoginCode);
			password = Utils.devExceptString(password);
			List<?> list = LoginMethods.getSysUser(userLoginCode);
			if (list.size() > 0) {
				HashMap<String, String> loginPerson = (HashMap<String, String>) list.get(0);
				String userId = loginPerson.get("USER_LOGINCODE");
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("userId", userId);
				params.put("password", MD5.md5(userId + password));
				/** 进行验证 */
				Map userMap = loginService.getUserByUserId(params);
				if (userMap != null) {
					if(userMap.get("STATE").equals("1")){
						msg = "登录成功！";
						LoginMethods.setSession(request, userMap);
						// 以用户id为key键存入map中，以判断下一次登录的人
						SessionListener.sessionMap.put(userId, request.getSession().getId());
						String loginUserType = (String) userMap.get("USER_TYPE");
						String loginUserState = (String) userMap.get("STATE");
						returnJson.put("loginUserType", loginUserType);
						returnJson.put("success", true);
						//写入系统日志表
						params.put("action", "登录系统");
						params.put("result", "登录成功");
						params.put("loginUserId", userLoginCode);
						params.put("loginUserName", (String)userMap.get("USER_NAME"));
						params.put("loginAreaName", (String)userMap.get("AREA_NAME"));
						params.put("loginAreaCode", (String)userMap.get("AREA_CODE"));
						LogInfo.getInstance().option(params);
						printInfo(response, returnJson);
					}else{
						msg = "该账号被停用！";
					}
					
				} else {
					msg = "登录账号不存在或密码错误！";
				}
			} else {
				msg = "登录账号不存在或密码错误！";
			}

		/*} else {
			msg = "图形验证码错误！";
		}*/
		if (msg != null) {
			returnJson.put("msg", msg);
			returnJson.put("success", false);
			printInfo(response, returnJson);
		}

	}

	/**
	 * 
	 * 注销系统
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/loginout")
	public void loginout(HttpServletRequest request, HttpServletResponse response) {
		LoginMethods.removeSession(request);
		try {
			response.sendRedirect(request.getContextPath() + "/loginController/logins.shtml");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	

	/**
	 * 登录成功后进入主界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/home")
	public String loginhtml(HttpServletRequest request) {
		request.setAttribute("userName", request.getSession().getAttribute(Constants.USER_NAME_SESSION));
		request.setAttribute("userId", request.getSession().getAttribute(Constants.USER_ID_SESSION));
		return "home";
	}
	
	
	/**
	 * 404错误跳转
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/error404")
	public String error404(HttpServletRequest request) {
		return "system/common/error404";
	}
	
	/**
	 * 400错误跳转
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/error500")
	public String error500(HttpServletRequest request) {
		return "system/common/error500";
	}

	/**
	 * 登录成功后获取菜单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getUserMenus")
	public void getUserMenus(HttpServletRequest request, HttpServletResponse response) {
		JSONObject returnJson = new JSONObject();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("userId", Common.getLoginUserId(request));
		params.put("path", (String) request.getContextPath());
		String menu = loginService.getUserMenus(params);
		returnJson.put("menu", menu);
		printInfo(response, returnJson);
	}

	/**
	 * 平台唯一登录入口
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/logins")
	public String logins(HttpServletRequest request) {
		String pageLabel = RandomTool.randString(16);
		request.getSession().setAttribute(pageLabel, "0");
		String desRandom = RandomTool.randNum(16); // 用于生成密钥的随机数
		request.getSession().setAttribute(Constants.DESSTRING, desRandom);
		request.getSession().setAttribute("desRandom", desRandom);
		request.getSession().setAttribute("pageLabel", pageLabel);
		return "smart-login";
	}

	/**
	 * 生成图片验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/imge")
	public String imge(HttpServletRequest request, HttpServletResponse response) {
		// 创建验证码图片
		Map<String, BufferedImage> codeImage = ImageUtil.createImage();
		// 放入session，只放key
		String code = codeImage.keySet().iterator().next();
		request.getSession().setAttribute("CheckCode", code);
		// 将图片取出，并转换为输入流
		BufferedImage image = codeImage.get(code);
		InputStream in = null;
		try {
			in = ImageUtil.getInputStream(image);
			OutputStream os = response.getOutputStream(); // 创建输出流
			byte[] b = new byte[1024];
			while (in.read(b) != -1) {
				os.write(b);
			}
			in.close();
			os.flush();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

}
